package com.owen.shiro;

import com.owen.pojo.Users;
import com.owen.service.UsersService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

import javax.lang.model.element.VariableElement;

/**
 * 自定义Realm
 */
public class UserRealm extends AuthorizingRealm {

    @Autowired
    private UsersService usersService;

    // 执行授权逻辑
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        // 给资源授权
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        // 获取当前登录用户
        Subject subject = SecurityUtils.getSubject();
        // 即return new SimpleAuthenticationInfo(users,users.getPassword(),"");中的第一个参数
        Users users = (Users)subject.getPrincipal();


        // 到数据库查询当前用户的权限
        Users users1 = usersService.selectUserById(users.getId());

        // 执行授权，（添加授权字符串）
        simpleAuthorizationInfo.addStringPermission(users.getPerms());

        return simpleAuthorizationInfo;
    }


    // 执行认证逻辑
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken token = (UsernamePasswordToken)authenticationToken;
        // 获取用户名
        String username = token.getUsername();
        Users users = usersService.selectUserByName(username);

        // 判断用户名是否存在（用户名是否正确）
        if(users == null){
            // 用户名不存在
            return null;// Shiro底层会抛出UnknownAccountException异常
        }

        // 判断密码 password是数据库中正确的密码
        return new SimpleAuthenticationInfo(users,users.getPassword(),"");
    }
}